package com.biscuit.page.basicservice.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.biscuit.common.base.BaseListResponse;
import com.biscuit.common.base.BaseResponse;
import com.biscuit.common.base.BaseResponseVoid;
import com.biscuit.page.basicservice.api.model.request.collection.CollectionSaveAReq;
import com.biscuit.page.basicservice.api.model.response.collection.CollectionAResp;
import com.biscuit.page.basicservice.api.model.response.collection.CollectionSaveAResp;
import com.biscuit.page.basicservice.api.model.response.collection.DefaultCollectionRefreshStatusAResp;
import com.biscuit.page.basicservice.bean.RedisCache;
import com.biscuit.page.basicservice.conf.handler.UserContextHandler;
import com.biscuit.page.basicservice.persistence.dao.CollectionDao;
import com.biscuit.page.basicservice.model.entities.mongo.DefaultCollection;
import com.biscuit.page.basicservice.model.entities.mysql.SysCollection;
import com.biscuit.page.basicservice.service.api.MongoService;
import com.biscuit.page.basicservice.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author mazihao
 * @createTime 2024/3/26 9:28
 */
@Slf4j
@Service
public class CollectionService {

    @Resource
    private CollectionDao collectionDao;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MongoService mongoService;

    public BaseResponse<BaseListResponse<CollectionAResp>> getCollectionList() {
        BaseListResponse<CollectionAResp> response = new BaseListResponse<>();
        List<CollectionAResp> listResponse = new ArrayList<>();

        // 从 mongodb 中获取默认收藏想列表
        List<DefaultCollection> defaultCollectList = this.mongoService.list(DefaultCollection.class);

        // 从数据库获取用户收藏列表，登录时获取
        List<SysCollection> accountCollectList = null;
        if (UserContextHandler.isLogin()) {
            accountCollectList = this.collectionDao.getListByUserId(UserContextHandler.getUserId());
        }

        // 列表不为空时合并进行类型转换，转换为接口返回类型
        if (CollectionUtils.isNotEmpty(defaultCollectList)) {
            listResponse.addAll(
                    defaultCollectList.stream().map(x -> {
                        CollectionAResp item = new CollectionAResp();
                        BeanUtils.copyProperties(x, item);
                        item.setIsAdd(Boolean.FALSE);
                        item.setIsDefault(Boolean.TRUE);
                        return item;
                    }).sorted(Comparator.comparing(CollectionAResp::getOrdered)).collect(Collectors.toList())
            );
        }
        if (CollectionUtils.isNotEmpty(accountCollectList)) {
            listResponse.addAll(
                    accountCollectList.stream().map(x -> {
                        CollectionAResp item = new CollectionAResp();
                        BeanUtils.copyProperties(x, item);
                        item.setIsAdd(Boolean.FALSE);
                        item.setIsDefault(Boolean.FALSE);
                        return item;
                    }).sorted(Comparator.comparing(CollectionAResp::getOrdered)).collect(Collectors.toList())
            );
        }
        response.setList(listResponse);
        return BaseResponseUtil.success(response);
    }

    /**
     * 保存或修改用户收藏项
     *
     * @param req 基本参数
     * @return
     */
    public BaseResponse<CollectionSaveAResp> saveCollection(CollectionSaveAReq req) {
        // 条件判断
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getTitle()), "收藏项标题为空");
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getUrl()), "收藏项标链接为空");

        // 属性赋值
        CollectionSaveAResp response = new CollectionSaveAResp();
        response.setOrdered(req.getOrdered());
        SysCollection sysCollection = new SysCollection();
        BeanUtils.copyProperties(req, sysCollection);
        if (StringUtils.isNotBlank(req.getId())) {
            sysCollection.setId(Long.parseLong(req.getId()));
        }
        if (!NumberUtil.numberCheck(sysCollection.getOrdered())) {
            // 查询当前用户收藏项数量
            int count = this.collectionDao.getCountByUserId(UserContextHandler.getUserId()) + 1;
            sysCollection.setOrdered(count);
            response.setOrdered(count);
        }

        // 根据页面地址爬取图标
        sysCollection.setIconUrl(CommonUtil.getIconUrlByUrl(req.getUrl()));

        // 设置收藏向别名
        sysCollection.setIconAlias(req.getTitle().substring(0, 1).toUpperCase());
        sysCollection.setUserId(UserContextHandler.getUserId());

        // 新增/保存收藏项
        sysCollection = this.collectionDao.saveAccountCollection(sysCollection);

        // 设置返回收藏数据
        response.setId(sysCollection.getId().toString());
        response.setIconUrl(sysCollection.getUrl());
        response.setIconAlias(sysCollection.getIconAlias());

        // 执行保存操作并返回数据
        return BaseResponseUtil.success(response);
    }


    /**
     * 保存或修改默认收藏项
     *
     * @param req 基本参数
     * @return
     */
    public BaseResponse<BaseResponseVoid> saveDefaultCollection(CollectionSaveAReq req) {
        // 条件判断
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getTitle()), "收藏项标题为空");
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getUrl()), "收藏项标链接为空");

        // 属性赋值
        DefaultCollection defaultCollection = new DefaultCollection();
        BeanUtils.copyProperties(req, defaultCollection);
        if (!NumberUtil.numberCheck(defaultCollection.getOrdered())) {
            defaultCollection.setOrdered(0);
        }

        // 根据页面地址爬取图标
        defaultCollection.setIconUrl(CommonUtil.getIconUrlByUrl(req.getUrl()));

        // 设置图标显示别名
        defaultCollection.setIconAlias(req.getTitle().substring(0, 1).toUpperCase());

        // 新增/修改默认收藏项
        this.collectionDao.saveDefaultCollection(defaultCollection);

        // 更新缓存更改状态
        // redisCache.set(RedisConstant.DEFAULT_COLLECTION_UPDATE_STATUS, String.valueOf(1), );

        return BaseResponseUtil.success();
    }

    public BaseResponse<BaseResponseVoid> delCollectionById(Long id) {
        BaseExceptionUtil.throwException(Objects.nonNull(id) && id > 0, "收藏项Id为空");
        this.collectionDao.updateDeleteById(id);
        return BaseResponseUtil.success();
    }

    public BaseResponse<BaseResponseVoid> delDefaultCollectionById(String id) {
        this.mongoService.deleteById(DefaultCollection.class, id);
        return BaseResponseUtil.success();
    }

    public BaseResponse<DefaultCollectionRefreshStatusAResp> getDefaultCollectionUpdateStatus() {
        // DefaultCollectionRefreshStatusAResp request = new DefaultCollectionRefreshStatusAResp();
        // Object valueObj = redisUtil.get(RedisConstant.DEFAULT_COLLECTION_UPDATE_STATUS);
        // if (Objects.nonNull(valueObj)) {
        //     request.setStatus(Integer.parseInt(valueObj.toString()));
        // } else {
        //     request.setStatus(0);
        //     redisUtil.set(RedisConstant.DEFAULT_COLLECTION_UPDATE_STATUS, 0);
        // }
        // return BaseResponseUtil.success(request);
        return BaseResponseUtil.success();
    }
}
